package cn.tedu.stock.service.impl;

import cn.tedu.stock.mapper.StockMapper;
import cn.tedu.stock.service.StockService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class StockServiceImpl implements StockService {
    @Autowired
    private StockMapper stockMapper;

    /**
     * 新增购物车的时候检查库存数量
     * @param productCode
     * @return
     */
    @Override
    public Integer checkStock(String productCode) {
        log.info("开始检查库存数量,传入的参数：productCode={}",productCode);
        // 添加参数校验
        if (productCode == null || productCode.trim().isEmpty()) {
            log.warn("商品编码不能为空");
            return null;
        }
        Integer stockCount = stockMapper.checkStock(productCode);
        log.info("检查库存数量结束，结果为：stockCount={}", stockCount);
        return stockCount;
    }

    /**
     * 减少库存数量
     * @param productCode
     * @param count
     * @return
     */
    @Override
    public Boolean reduceStock(String productCode, Integer count) {
        log.info("开始减少库存数量,传入的参数：productCode={},count={}",productCode,count);
        // 添加参数校验
        if (productCode == null || productCode.trim().isEmpty()) {
            log.warn("商品编码不能为空");
            return false;
        }
        if (count == null || count <= 0) {
            log.warn("扣减数量必须大于0");
            return false;
        }
        Integer result = stockMapper.reduceStock(productCode, count);
        log.info("减少库存数量结束，结果为：result={}", result);

        // 改进返回值判断
        if (result == null || result < 1) {
            log.info("库存没有减少成功，可能是库存不足");
            return false;
        }
        log.info("库存减少成功");
        return true;
    }
}
